package com.lfg.leetcode.leetcode0;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

public class No99recoverTree {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(1);
        root.right = new TreeNode(4);
        root.right.left = new TreeNode(2);
        recoverTree(root);
        System.out.println("[" + root.val + "]");
    }

    public static void recoverTree(TreeNode root) {
        List<Integer> nums = new ArrayList<>(100);
        List<TreeNode> nodes = new ArrayList<>(100);
        recoverTree(root, nums, nodes);
        List<Integer> data = new ArrayList<>(nums);
        Collections.sort(data);
        int index = 0;

        for (; index < data.size(); index++) {
            if (!Objects.equals(data.get(index), nums.get(index))) {
                break;
            }
        }
        Integer dest = data.get(index);
        for (TreeNode node : nodes) {
            if (node.val == dest) {
                node.val = nums.get(index);
            }
        }
        nodes.get(index).val = dest;

    }

    public static void recoverTree(TreeNode root, List<Integer> nums, List<TreeNode> nodes) {
        if (root == null) {
            return;
        }
        recoverTree(root.left, nums, nodes);
        nums.add(root.val);
        nodes.add(root);
        recoverTree(root.right, nums, nodes);
    }

}

